﻿
using DotLiquid;

namespace Jim.Web.Core;

public static class DotliquidHelper
{
    public static string BuildByObject(string sqlTemplate, object obj,Action<Template> temp = null)
    {
        Liquid.UseRubyDateFormat = true;
        Template.NamingConvention = new DotLiquid.NamingConventions.RubyNamingConvention();
        Template.RegisterFilter(typeof(DotliquidCustomFilter));
        Template.RegisterTag<ConditionalTag>("conditional");
        Template.FileSystem = new DotliquidTemplateFileSystem();
        Template template = Template.Parse(sqlTemplate);//解析传入模版
        if(temp != null) temp.Invoke(template);
        var sql = template.Render(Hash.FromAnonymousObject(obj));//渲染传入模版
        return sql;
    }

    public static string BuildByDic(string sqlTemplate, Dictionary<string, object> dic)
    {
        Liquid.UseRubyDateFormat = true;
        Template.NamingConvention = new DotLiquid.NamingConventions.RubyNamingConvention();
        Template.RegisterFilter(typeof(DotliquidCustomFilter));
        Template.RegisterTag<ConditionalTag>("conditional");
        Template.FileSystem = new DotliquidTemplateFileSystem();
        Template template = Template.Parse(sqlTemplate);//解析传入模版
        var sql = template.Render(Hash.FromDictionary(dic));
        return sql;
    }
    public static string BuildByJson(string sqlTemplate, string json)
    {
        Liquid.UseRubyDateFormat = true;
        Template.NamingConvention = new DotLiquid.NamingConventions.RubyNamingConvention();
        Template.RegisterFilter(typeof(DotliquidCustomFilter));
        Template.RegisterTag<ConditionalTag>("conditional");
        Template.FileSystem = new DotliquidTemplateFileSystem();
        Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
        return BuildByDic(sqlTemplate, dic);
    }

    public static string BuildFromFileByDic(string formId, Dictionary<string, object> dic)
    {
        var sqlTemplate = GetTemplate(formId);
        return BuildByDic(sqlTemplate, dic);
    }
    public static string BuildFromFileByJson(string formId, string json)
    {
        var sqlTemplate = GetTemplate(formId);
        return BuildByJson(sqlTemplate, json);
    }
    public static string BuildFromFileByObject(string formId, object obj)
    {
        var templateName = GetTemplate(formId);
        return BuildByObject(templateName, obj);
    }


    public static string GetTemplate(string templateName)
    {
        // 基础目录
        string basePath = AppDomain.CurrentDomain.BaseDirectory;
        var templatePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "Template");
        // 完整目录
        string fullPath = Path.Combine(templatePath, templateName);
        if (File.Exists(fullPath))
        {
            // 读取模板文件
            string templateFile = File.ReadAllText(fullPath);
            return templateFile;
        }
        else
        {
            return "";
        }
    }

}
